import cv2 as cv
import numpy as np

def myresize(srcimg,shrink_size):
    # srcimg = cv.imread(string, 1)
    height, width = srcimg.shape[:2]
    size = (int(width * shrink_size), int(height * shrink_size))
    shrink = cv.resize(srcimg, size, interpolation=cv.INTER_AREA)
    return shrink


#harris 算子
def myharris(string):
    #open the image
    str2=string+"harris"
    srcimg = cv.imread(string, 1)
    gray = cv.cvtColor(srcimg,cv.COLOR_BGR2GRAY)
    gray = np.float32(gray)
    HarrisImg = cv.cornerHarris(gray,2,3,0.04)
    # img 输入图像，数据类型为float32
    # blockSize 角点检测当中的邻域值。
    # ksize 使用Sobel函数求偏导的矩阵大小
    # k 角点检测参数，取值为0.04到0.06(用于阈值化)
    HarrisImg = cv.dilate(HarrisImg,None)#图像膨胀 扩大标记的点
    srcimg[HarrisImg>0.02*HarrisImg.max()]=[0,0,255]#角点位置用颜色标记[B,G,R]
    cv.imshow(str2,srcimg)
    # cv.imshow("HarrisImg",HarrisImg)


#SIFT 算子
def mySIFT(string):
    #open the image
    str2=string+"SIFT"
    img = cv.imread(string, 1)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    sift =cv.xfeatures2d.SIFT_create() #不能用cv.SIFT(),xfeatures2d需要pip install opencv-contrib-python
    kp =sift.detect(gray,None)#finds the keypoint in the images.
    img=cv.drawKeypoints(gray, kp, None, color=(255,0,0))#draws the small circles on the locations of keypoints
    # img = cv.drawKeypoints(gray, kp, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    # #draw a circle with sizeof keypoint and it will even show its orientation
    cv.imshow(str2,img)



def myFAST(string):
    str2 = string + "FAST"
    img = cv.imread(string,1)
    # gray =myresize(img, 0.5)
    gray =cv.pyrDown(img)
    # gray= cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    fast = cv.FastFeatureDetector.create()
    # fast=cv.FastFeatureDetector_create()
    # # find and draw the keypoints
    kp=fast.detect(gray,None)
    img2 = cv.drawKeypoints(gray, kp, None, color=(0,255, 0))
    print("Threshold: ", fast.getThreshold()) # #print all default param
    print("nonmaxSuppression: ", fast.getNonmaxSuppression())
    print("neighborhood: ", fast.getType())
    print("Total Keypoints with nonmaxSuppression: ", len(kp))
    cv.imshow(str2+"fast_true",img2)
    # 不使用非极大值抑制
    fast.setNonmaxSuppression(0)
    kp =fast.detect(img,None)
    print("Total Keypoints without nonmaxSuppreion:",len(kp))
    img3 =cv.drawKeypoints(img,kp,None, color=(0,255,0))
    cv.imshow(str2+"fast_false",img3)

def myORB(string):
    str2 = string + "ORB"
    img = cv.imread(string, 0)
    orb=cv.ORB_create()

    #找关键点
    kp=orb.detect(img,None)
    #用ORB计算描述符
    kp,des=orb.compute(img,kp)
    #画出关键点
    img2=cv.drawKeypoints(img, kp, None, color=(0, 255,0))
    cv.imshow(str2,img2)



myharris("chessboard.png")
myharris("timg.jpg")
mySIFT("chessboard.png")
mySIFT("timg.jpg")
myFAST("chessboard2.png")
myFAST("timg.jpg")
myORB("chessboard2.png")
myORB("timg.jpg")
cv.waitKey()
cv.destroyAllWindows()